#!/usr/bin/env python
from __future__ import division
import cv2
import numpy as np
import io
import picamera
from optparse import OptionParser

def draw_rectangle(event,x,y,flags,param):
    global croprect, drawing
    resolution = np.array((0, 0))
    if event == cv2.EVENT_LBUTTONUP:
        croprect[1] = (x, y)
        if not drawing:
            croprect[0] = (x, y)
        else:
            calc_rect()
        drawing = not drawing
    elif (event == cv2.EVENT_MOUSEMOVE) and drawing:
        croprect[1] = (x, y)

def calc_rect():
    resolution = abs(croprect[1] - croprect[0] + 1) // 2 * 2
    for x in range(0, 2):
        if croprect[0][x] < croprect[1][x]:
            croprect[0][x] = (croprect[0][x] - 1) // 2 * 2
        elif (croprect[0][x] > croprect[1][x]):
            croprect[0][x] = (croprect[0][x] + 1 - resolution[x]) // 2 * 2
        croprect[1][x] = croprect[0][x] + resolution [x]

parser = OptionParser("extract.py Width Height")
(parameter, args) = parser.parse_args()
if len(args) != 2:
    parser.error("Not the right parameters")

drawing = False
cap = cv2.VideoCapture(0)
croprect = np.array(((0, 0), (100, 100)))
stream = io.BytesIO()
camera = picamera.PiCamera()
camera.resolution = (int(args[0]), int(args[1]))
camera.vflip = True

cv2.namedWindow('frame')
cv2.namedWindow('extract')
cv2.setMouseCallback('frame',draw_rectangle)

while(True):
    camera.capture(stream, format='jpeg')
    data = np.fromstring(stream.getvalue(), dtype=np.uint8)
    frame = cv2.imdecode(data, 1)
    if drawing:
        cv2.rectangle(frame, tuple(croprect[0]), tuple(croprect[1]), (0,0,0), 1)
    else :
        cropimage = frame[croprect[0][1]:croprect[1][1], croprect[0][0]:croprect[1][0]]
        cv2.imshow('extract', cropimage)
        cropimage = cv2.cvtColor(cropimage, cv2.COLOR_BGR2YUV_YV12)
        
        """
        Now give to the send library croprect for resolution and cropiamge for the YUV data
        """
        
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    
cap.release()
cv2.destroyAllWindows()
